﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using ProgramMain.Database;
using ProgramMain.Database.SimpleOpticNetDBTableAdapters;
using ProgramMain.Framework;
using ProgramMain.Google;

namespace ProgramMain.OpticNet
{
    public partial class CableTunnelDistanceEdit : ProgramMain.Framework.BaseDetailCtl
    {
        // Класс события изменения координат

        public class CoordinateChange:EventArgs
        {
            public Coordinate OldCoordinate { get; private set; }
            public Coordinate NewCoordinate { get; private set; }

            public CoordinateChange(Coordinate oldCoordinate, Coordinate newCoordinate)
            {
                this.OldCoordinate = oldCoordinate;
                this.NewCoordinate = newCoordinate;
            }
        }

        public CableTunnelDistanceEdit()
        {
            InitializeComponent();
        }

        private SimpleOpticNetDB.VertexesRow _vertex1;
        private SimpleOpticNetDB.VertexesRow _vertex2;

        private Coordinate coordinate1;
        private Coordinate coordinate2;

        public event EventHandler<IntEvent> ReLoadVertex1;
        public event EventHandler<IntEvent> ReLoadVertex2;
        public event EventHandler<CableTunnelDistanceEdit.CoordinateChange> CoordinateChanged;

        private int? _ActiveVertexID = null;
        private decimal _length;

        public decimal Length
        {
            get { return _length; }
            set
            {
                _length = value;
                labelDistace.Text = (_length + _Delta).ToString();
            }
        }

        private int _Delta = 0;

        public bool SaveRedirect()
        {
            if (_Delta == 0) return true;
            DialogResult dialogResult
                =  XtraMessageBox.Show("Сохранить изменение туннеля", "Сообщение", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning);
            if (dialogResult == DialogResult.Cancel ) return false;
            if(dialogResult == DialogResult.Yes) SaveCoordinate();
            return true;
        }

        private void SetPictureVertex(int param, SimpleOpticNetDB.VertexesRow vertexesRow, bool active)
        {
            DevExpress.XtraEditors.PictureEdit pictureEdit = param == 0 ? pictureVertex1 : pictureVertex2;
            DevExpress.XtraEditors.LabelControl caption = param == 0 ? labelCaption1 : labelCaption2;

            if (vertexesRow.IsIsEmptyNull() || vertexesRow.IsEmpty)
                pictureEdit.Image = active ? Properties.Resources.lightvertex_24 : Properties.Resources.transitvertex_24;
            else
            {
                if (vertexesRow.IsImageIndexNull() || vertexesRow.ImageIndex != 1)
                    pictureEdit.Image = active ? Properties.Resources.lightvertex_24 : Properties.Resources.vertex_24;
                else if (_vertex1.ImageIndex == 1)
                    pictureEdit.Image = active ? Properties.Resources.lightoffice_24 : Properties.Resources.office_24;
                else if (_vertex1.ImageIndex == 2)
                    pictureEdit.Image = active ? Properties.Resources.lightoffice_24 : Properties.Resources.house_24;
                else if (_vertex1.ImageIndex == 3)
                    pictureEdit.Image = active ? Properties.Resources.lightoffice_24 : Properties.Resources.CBVertes_24;
                else
                    pictureEdit.Image = active ? Properties.Resources.lightvertex_24 : Properties.Resources.vertex_24;
            }

            caption.ForeColor = active ? Color.Red : Color.Black;
        }
        private void SetVertex(int param)
        {
            if (param == 0)
            {
                if (dataSourceVertex.Current != null)
                {
                    _vertex1 = (SimpleOpticNetDB.VertexesRow)((DataRowView)dataSourceVertex.Current).Row;
                    if (!_vertex1.IsCaptionNull())
                    {
                        labelCaption1.Text = _vertex1.Caption;
                        SetPictureVertex(param, _vertex1, false);
                        coordinate1 = new Coordinate(_vertex1.Longitude,_vertex1.Latitude);
                    }
                }
            }

            if (param == 1)
            {
                if (dataSourceVertex.Current != null)
                {
                    _vertex2 = (SimpleOpticNetDB.VertexesRow) ((DataRowView) dataSourceVertex.Current).Row;
                    if (!_vertex2.IsCaptionNull())
                    {
                        labelCaption2.Text = _vertex2.Caption;
                        SetPictureVertex(param, _vertex2, false);
                        coordinate2 = new Coordinate(_vertex2.Longitude, _vertex2.Latitude);
                    }
                }
            }
        }

        private SimpleOpticNetDB.CableTunnelsDataTable tunnelsDataTable;

        private void LoadCableTunnel()
        {
            #region чтения тунеля
            CableTunnelsTableAdapter cableTunnelsTableAdapter = new CableTunnelsTableAdapter();
            cableTunnelsTableAdapter.ClearBeforeFill = true;
            cableTunnelsTableAdapter.SelectCommandTimeout = Properties.Settings.Default.LongQueryTimeout;
            tunnelsDataTable = cableTunnelsTableAdapter.GetData(DetailID,
                                                                                                       null, null, null,
                                                                                                       null, null, null, null, null);
           
            if (tunnelsDataTable.Count > 0)
            {
                Length =
                    (decimal)
                    Math.Round(
                        new Coordinate(tunnelsDataTable[0].Latitude1, tunnelsDataTable[0].Longitude1).Distance(new Coordinate(tunnelsDataTable[0].Latitude2, tunnelsDataTable[0].Longitude2)),0);
            }
            #endregion
        }

        private void CableTunnelDistanceEdit_DetailIDChanged(object sender, Framework.DetailEventArgs e)
        {
            LoadCableTunnel();
            this.vertexesTableAdapter.ClearBeforeFill = true;
            this.vertexesTableAdapter.Fill(this.simpleOpticNetDB.Vertexes, null, null, null, null, null, null, null, null, DetailID);
            if (dataSourceVertex.Count > 1)
            {
                dataSourceVertex.Position = 0;
                SetVertex(dataSourceVertex.Position);

                dataSourceVertex.Position = 1;
                SetVertex(dataSourceVertex.Position);
            }

            if (ReLoadVertex1 != null && _vertex1 != null) ReLoadVertex1(this, new IntEvent(_vertex1.ID));
            if (ReLoadVertex2 != null && _vertex2 != null) ReLoadVertex2(this, new IntEvent(_vertex2.ID));
            _Delta = 0;
            _ActiveVertexID = null;
        }

        private void pictureVertex1_EditValueChanged(object sender, EventArgs e)
        {

        }

        private void pictureVertex1_Click(object sender, EventArgs e)
        {
            if (sender is DevExpress.XtraEditors.PictureEdit)
                try
                {
                    _ActiveVertexID = Convert.ToInt32(((DevExpress.XtraEditors.PictureEdit)sender).Tag);
                    if (_ActiveVertexID.Value == 0)
                    {
                        SetPictureVertex(0, _vertex1, true);
                        SetPictureVertex(1, _vertex2, false);
                    }
                    if (_ActiveVertexID.Value == 1)
                    {
                        SetPictureVertex(0, _vertex1, false);
                        SetPictureVertex(1, _vertex2, true);
                    }
                }
                catch (Exception)
                {
                }
        }

       private Coordinate _recalkCoordinate(SimpleOpticNetDB.VertexesRow fix, SimpleOpticNetDB.VertexesRow edit, int delta)
        {
            Coordinate res = new Coordinate(edit.Longitude,edit.Latitude);
            #region Latitude

            {
                decimal d = Math.Round(fix.Latitude - edit.Latitude, 5);
                decimal si = d / Length;
                decimal newD = Math.Round(si * (Length + delta), 5);
                res.Latitude = (double)Math.Round(fix.Latitude - newD, 5);
            }
            #endregion

            #region Longitude
            {

                decimal d = Math.Round(fix.Longitude - edit.Longitude, 5);
                decimal si = d / Length;
                decimal newD = Math.Round(si * (Length + delta), 5);
                res.Longitude = (double)Math.Round(fix.Longitude - newD, 5);
            }
            #endregion

            return res;
        }

        private void simpleButton2_Click(object sender, EventArgs e)
        {
            if (!_ActiveVertexID.HasValue)
            {
                XtraMessageBox.Show("Не выбран объект(колодец) для движения. \n\r Выбирите объект(колодец).",
                                    "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            _Delta++;
            if (_ActiveVertexID.Value == 1)
            {
                coordinate2 = _recalkCoordinate(_vertex1, _vertex2, _Delta);
                if (CoordinateChanged != null)
                    CoordinateChanged(this,
                                      new CoordinateChange(new Coordinate(_vertex2.Longitude, _vertex2.Latitude),
                                                           coordinate2));
            }

            if (_ActiveVertexID.Value == 0)
            {
                coordinate1 = _recalkCoordinate(_vertex2, _vertex1, _Delta);
                if (CoordinateChanged != null)
                    CoordinateChanged(this,
                                      new CoordinateChange(new Coordinate(_vertex1.Longitude, _vertex1.Latitude),
                                                           coordinate1));
            }
            labelDistace.Text = (_length + _Delta).ToString();
        }

        private void simpleButton1_Click(object sender, EventArgs e)
        {
            if (!_ActiveVertexID.HasValue)
            {
                XtraMessageBox.Show("Не выбран объект(колодец) для движения. \n\r Выбирите объект(колодец).",
                                    "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            _Delta--;
            if (_ActiveVertexID.Value == 1)
            {
                coordinate2 = _recalkCoordinate(_vertex1, _vertex2, _Delta);
                if (CoordinateChanged != null)
                    CoordinateChanged(this,
                                      new CoordinateChange(new Coordinate(_vertex2.Longitude, _vertex2.Latitude),
                                                           coordinate2));
            }

            if (_ActiveVertexID.Value == 0)
            {
                coordinate1 = _recalkCoordinate(_vertex2, _vertex1, _Delta);
                if (CoordinateChanged != null)
                    CoordinateChanged(this,
                                      new CoordinateChange(new Coordinate(_vertex1.Longitude, _vertex1.Latitude),
                                                           coordinate1));
            }
            labelDistace.Text = (_length + _Delta).ToString();
        }

        public void SaveCoordinate()
        {
            tunnelsDataTable[0].Length = _length + _Delta;// (decimal)Math.Round(coordinate1.Distance(coordinate2), 2);
            CableTunnelsTableAdapter cableTunnelsTableAdapter = new CableTunnelsTableAdapter();
            cableTunnelsTableAdapter.ClearBeforeFill = true;
            cableTunnelsTableAdapter.SelectCommandTimeout = Properties.Settings.Default.LongQueryTimeout;
            cableTunnelsTableAdapter.Update(tunnelsDataTable);

            _vertex1.Latitude = (decimal)coordinate1.Latitude;
            _vertex1.Longitude = (decimal)coordinate1.Longitude;
            _vertex1.EndEdit();

            _vertex2.Latitude = (decimal)coordinate2.Latitude;
            _vertex2.Longitude = (decimal)coordinate2.Longitude;
            _vertex2.EndEdit();
            vertexesTableAdapter.Update(simpleOpticNetDB.Vertexes);
        }

        private void labelDistace_TextChanged(object sender, EventArgs e)
        {
           //int i = (panelTunnel.Width - pictureVertex1.Width - pictureVertex2.Width)/2;
           // labelDistace.Location = new Point(i - labelDistace.Width/2, labelDistace.Location.Y);
        }
    }
}